#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

#define THRNUM 	20
#define FNAME	"out"
#define LINESIZE	1024

//初始化互斥量
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//线程处理函数
static void * thr_add(void * p)
{
	char linebuf[LINESIZE];
	//打开文件
	FILE * fp = fopen(FNAME, "r+");
	if(fp == NULL)
	{
		perror("fopen");
		exit(1);
	}

	pthread_mutex_lock(&mutex);				//上锁
	fgets(linebuf, LINESIZE, fp);			//读取文件内容
	fseek(fp, 0, SEEK_SET);					//定位到文件首
	fprintf(fp, "%d\n", atoi(linebuf) + 1);	//把新数据写入
	fclose(fp);								//关闭文件
	pthread_mutex_unlock(&mutex);			//解锁

	//结束线程
	pthread_exit(NULL);
}

int main()
{
	int i, err;
	pthread_t tid[THRNUM];
	//循环20次
	for(i = 0; i < THRNUM; i++)
	{
		err = pthread_create(&tid[i], NULL, thr_add, NULL);
		if(err)
		{
			fprintf(stderr, "create:%s", strerror(err));
			exit(1);
		}
	}
	//回收线程
	for(i = 0; i < THRNUM; i++)
	{
		pthread_join(tid[i], NULL);
	}
	//销毁互斥量
	pthread_mutex_destroy(&mutex);
	exit(0);
}